<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 
 * 后台管理员角色控制器
 * @author 66diqiu-li
 *
 */
class Admin_Adminrole_module extends CI_Module {
	
    private $sid;
	/**
	 * 
	 * 构造函数
	 */
    public function __construct(){
    	parent::__construct();
    	$this->sid = $GLOBALS['sid'];
    	$this->load->model('admin.Adminrole_model');
    	$this->load->model('admin.Menu_model');
    	$this->load->model('admin.Adminroleauthors_model');
    	$this->load->model('admin.Adminuser_model');
    }
    
	/**
	 * 
	 * 管理员角色列表
	 */
    function index(){
    	
    	//查询条件
    	$condition = $this->input->post('condition')?$this->input->post('condition'):$this->input->get('condition');
    	$this->load->library('mycommonclass');
    	$where = $this->mycommonclass->str2where($condition);
    	
        $page_config['perpage']=20;   //每页条数
        $page_config['part']=2;//当前页前后链接数量
        $page_config['url']='admin/adminrole/index';//url
        $page_config['param'] = '?condition='.$condition;//参数
        $page_config['seg']=4;//参数取 index.php之后的段数，默认为3，即index.php/control/function/18 这种形式
        $page_config['nowindex']=$this->uri->segment($page_config['seg']) ? $this->uri->segment($page_config['seg']):1;//当前页
        $page_config['total'] = $this->Adminrole_model->get_count($where);
        
        $this->load->library('mypageclass');
        $this->mypageclass->initialize($page_config);        
        $result = $this->Adminrole_model->get_list($page_config['perpage'],$page_config['nowindex'],$where);   
        $data['list'] = $result;
        $data['condition'] = $condition;
        $this->load->view('adminrole/adminrole_index',$data);
    }
    
    /**
     * 
     * 管理员角色添加页面
     */
    function add(){
    	//数据保存URL
        $data['form_post'] = site_url('admin/adminrole/save');
        $data['ajax_check_name'] = site_url('admin/adminrole/ajax_check_name?id=0');
        $this->load->view('adminrole/adminrole_add',$data);
    }
    
    /**
     * 
     * 管理员角色编辑页面
     */
    function edit(){    	
    	$id = $this->input->get('id');
    	$row = $this->Adminrole_model->get_row(array('id'=>$id));
        $data['row'] = $row;
        
    	//数据保存URL
        $data['form_post'] = site_url('admin/adminrole/save');
        $data['ajax_check_name'] = site_url("admin/adminrole/ajax_check_name?id=$id");
        $this->load->view('adminrole/adminrole_edit',$data);
    }
    
    /**
     * 
     * 管理员角色保存操作
     */
    function save(){
        $data = $this->input->post('Form');
        $id = $this->input->post('id');
        if(empty($id)){
        	
        	//操作日志
        	$log = array('action' => 'add');
        	
        	$data['add_time'] = date('Y-m-d H:i:s',now());
            $res = $this->Adminrole_model->add_row($data);
        }else{
        	//操作日志
        	$log = array('action' => 'edit');
        	
        	$data['edit_time'] = date('Y-m-d H:i:s',now());
            $res = $this->Adminrole_model->edit_row($data,array('id'=>$id));
        }
        if($res){
        	
        	//操作日志添加
        	$log['log'] = '后台管理角色('.$data['name'].')';
        	$this->_record_log($log);
        	
            $this->success('操作成功',site_url('admin/adminrole/index'),true);
        }else{
        	$this->error('操作失败',site_url('admin/adminrole/index'),true);
        }
    }
    
    /**
     * 
     * 设置角色权限
     */
    function set_authority(){
    	$role_id = $this->input->get('id');
    	if(empty($role_id)){
    	    $this->error('需要授权的角色不存在!',site_url('admin/adminrole/index'),1);
    	}
    	
    	//菜单数据
    	$result = $this->Menu_model->get_list(); 
    	
    	//获取已选择权限表数据
    	$priv_data = $this->Adminroleauthors_model->get_list(array('role_id'=>$role_id));
        $json = array();
        foreach ($result as $rs) {
            $data = array(
                'id' => $rs['id'],
                'checked' => $rs['id'],
                'parent_id' => $rs['parent_id'],
                'name' => $rs['name'] . ($rs['type'] == 0 ? "(菜单项)" : ""),
                'checked' => $this->Adminroleauthors_model->isCompetence($rs, $role_id, $priv_data) ? true : false,
                'open' => true,
            );
            $json[] = $data;
        }
    	$data = array(
    	    'json'=>json_encode($json),
    	    'role_id' => $role_id,
    	);
    	
    	$data['form_post'] = site_url('admin/adminrole/save_authority');
    	$this->load->view('adminrole/adminrole_authority',$data);
    }
    
    /**
     * 
     * 保存角色权限
     */
    function save_authority(){
    	$arg_post = $this->input->post();
    	$role_id = $arg_post['role_id'];
    	if(empty($arg_post['menu_id'])){
    		$this->error('没有需要授权的权限','',true);
    	}
    	$menuidAll = explode(',', $arg_post['menu_id']);
    	if (is_array($menuidAll) && count($menuidAll) > 0) {
            //菜单数据
            $menu_info = $this->Menu_model->get_menu_role(); 
            $addauthorize = array();
            //检测数据合法性
            foreach ($menuidAll as $menuid) {
            	if (empty($menu_info[$menuid])) {
            		continue;
            	}
            	$info = array(
            	    'app' => $menu_info[$menuid]['app'],
            	    'controller' => $menu_info[$menuid]['controller'],
            	    'action' => $menu_info[$menuid]['action'],
            	);
                $info['role_id'] = $role_id;
                $info['sid'] = $this->sid;
                $addauthorize[] = $info;
            }
            //添加新权限
            $res = $this->Adminroleauthors_model->add_batch($role_id,$addauthorize);
            if($res){
            	
        	    //操作日志
        	    $log = array('action' => 'add');
        	    $role_info = $this->Adminrole_model->get_row(array('id'=>$role_id));
	        	$log['log'] = '后台角色授权('.$role_info['name'].')';
	        	$this->_record_log($log);
        	
            	$this->success('授权成功!',site_url('admin/adminrole/index'),true);
            }else{
            	$this->error('授权失败!',site_url('admin/adminrole/index'),true);
            }
    	}else{
    		$this->error("没有接收到数据，执行清除授权成功！",site_url('admin/adminrole/index'),true);
    	}
    }
    
    /**
     * 
     * 删除操作
     */
    function ajax_remove(){
        $id = $this->input->get('id');
        if(empty($id)){
        	$post_id = $this->input->post('id');
        	
        	//判断是否存在管理员
        	$row = $this->Adminuser_model->get_row("role_id in ($post_id)");        	
        	if(!empty($row)){
        	    $this->error('该角色下面有管理员，不能删除','',true);
        	}
        	
        	$res = $this->Adminrole_model->remove_row("id in ($post_id)");
        	if($res){
	        	//删除角色相应数据
	        	$this->Adminroleauthors_model->remove_row("role_id in ($post_id)");
        	}
        }else{
            $row = $this->Adminuser_model->get_row(array('role_id'=>$id));

        	if(!empty($row)){
        	    $this->error('该角色下面有管理员，不能删除','',true);
        	}
        	
        	$role_info = $this->Adminrole_model->get_row(array('id'=>$id));

            if($role_info['name'] == '超级管理员'){
                $this->error('不能删除超级管理员','',true);
            }

            $res = $this->Adminrole_model->remove_row(array('id'=>$id));
            
            if($res){
        	    
        		//操作日志
        	    $log = array('action' => 'remove');
	        	$log['log'] = '后台管理员角色('.$role_info['name'].')';
	        	$this->_record_log($log);
            	
	        	//删除角色相应数据
	        	$this->Adminroleauthors_model->remove_row("role_id in ($id)");
            }
        }        
        if($res){
            $this->success('操作成功',site_url('admin/adminrole/index'),true);
        }else{
        	$this->error('操作失败','',true);
        }
    }
    
    /**
     * 
     * 修改状态信息
     */
    function ajax_status(){
	    $post = $this->input->post();
        $data[$post['field']] = $post['val'];
        $res = $this->Adminrole_model->edit_row($data,array('id'=>$post['id']));
        if($res){
            
        	//操作日志
            //查询角色名称
            $row = $this->Adminrole_model->get_row(array('id'=>$post['id']),'name');
            $log = array('action'=>'edit','log'=>'后台管理员角色('.$row['name'].')-状态值');
            $this->_record_log($log);
            
            $this->success('操作成功','',true);
        }else{
        	$this->error('操作失败','',true);
        }
    }
    
    /**
     * 
     * 判断管理员角色的名称是否存在
     */
    function ajax_check_name(){
        $arg_get = $this->input->get();
        $row = $this->Adminrole_model->get_row(array('name'=>$arg_get['Form']['name'],'id !='=>$arg_get['id']));
        if(!empty($row) && is_array($row)){
            $this->ajaxReturn('此管理员角色名称已存在!');
        }else{
            $this->ajaxReturn(true);
        }
    }
}